package ivo.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * Module: HttpClientUtil.java Description:
 * 以get/post的方式发送数据到指定的http接口---利用httpclient.jar包---HTTP接口的调用 Company: Author:
 * ptp Date: Feb 22, 2012
 */
public class HttpClientUtil {

	private static final Log eqpLogger = LogFactory.getLog("BCTOEQPT");
	private static final Log mesLogger = LogFactory.getLog("BCTOMES");


	/**
	 * @param //url
	 * @param //param
	 * @return
	 */

	public static String postMethodForMES(String url, String trx_id, String strInMsg){
		
		StringBuffer toMesMsg = new StringBuffer();
		StringBuffer frMesMsg = new StringBuffer();

//        toMesMsg.append("[" + AppContext.getCurrEventNumber() + "]");
//        frMesMsg.append("[" + AppContext.getCurrEventNumber() + "]");
//		toMesMsg.append("[" + url + "]");
//		frMesMsg.append("[" + url + "]");

		toMesMsg.append("[inTrx: " + strInMsg + "]");
		mesLogger.info(toMesMsg.toString());
		
		String returnMsg = null;
		//获取可关闭的 httpCilent
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //配置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
        		.setConnectTimeout(60000)
        		.setConnectionRequestTimeout(60000)
                .setSocketTimeout(60000)
                .setRedirectsEnabled(true)
                .build();
         
        HttpPost httpPost = new HttpPost(url);
        //设置超时时间
        httpPost.setConfig(requestConfig);
        //装配post请求参数
        List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); 
        list.add(new BasicNameValuePair("trxId", trx_id));  //请求参数
        list.add(new BasicNameValuePair("strInMsg", strInMsg)); //请求参数
        try {
        	
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8"); 
            //设置post求情参数
            httpPost.setEntity(entity);
            
            HttpResponse httpResponse = httpClient.execute(httpPost);
            
            if(httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200 ){
            	String responseMsg = EntityUtils.toString(httpResponse.getEntity());
            	System.out.println(responseMsg);
            	returnMsg = responseMsg.substring(1, responseMsg.length()-1).replaceAll("\\\\","");
            }
        } catch (Exception e) {
        	mesLogger.error(toMesMsg.toString());	
        	mesLogger.equals(frMesMsg.append("[ERROR:" + e.toString() + "]").toString());
        }finally {
            try {
                if(httpClient != null){
                    httpClient.close(); //释放资源
                }
            } catch (IOException ex) {
            	mesLogger.error(toMesMsg.toString());	
            	mesLogger.equals(frMesMsg.append("[ERROR:" + ex.toString() + "]").toString());
            }  
        }
        frMesMsg.append("[outTrx:" + returnMsg + "]");
        mesLogger.info(frMesMsg.toString());
        return returnMsg;
	}
	/*public static void asyncPostMethodMES(String url, String trx_id, String strInMsg){
		
		StringBuffer toMesMsg = new StringBuffer();
		StringBuffer frMesMsg = new StringBuffer();
		
		toMesMsg.append("MES_URL:" + url).append("--> toMES: " + strInMsg);
		frMesMsg.append("MES_URL:" + url);
		
		mesLogger.info(toMesMsg.toString());
		
		//获取可关闭的 httpCilent
		CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        //配置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
        		.setConnectTimeout(60000)
        		.setConnectionRequestTimeout(60000)
                .setSocketTimeout(60000)
                .setRedirectsEnabled(true)
                .build();
         
        HttpPost httpPost = new HttpPost(url);
        //设置超时时间
        httpPost.setConfig(requestConfig);
        //装配post请求参数
        List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); 
        list.add(new BasicNameValuePair("trxId", trx_id));  //请求参数
        list.add(new BasicNameValuePair("strInMsg", strInMsg)); //请求参数
        
        CountDownLatch latch = new CountDownLatch(1);
        try {
        	 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8"); 
             //设置post求情参数
             httpPost.setEntity(entity);
             httpClient.start();
	         httpClient.execute(httpPost, new FutureCallback<HttpResponse>() {
	
		        public void completed(final HttpResponse response) {
		            latch.countDown();
		            try {
		                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
		                String returnMsg = content.substring(1, content.length()-1).replaceAll("\\\\","");
		                frMesMsg.append("--> frMES: " + returnMsg);
		                mesLogger.info(frMesMsg.toString());
		            } catch (IOException e) {
		            	mesLogger.error(toMesMsg.toString());
		            	mesLogger.error(frMesMsg.append("--> frMES: ").append(e.toString()).toString());
		            }
		        }
		        public void failed(final Exception ex) {
		            latch.countDown();
		            mesLogger.error(toMesMsg.toString());
		            mesLogger.error(frMesMsg.append("--> frMES: ").append(ex.toString()).toString());
		        }
	
		        public void cancelled() {
		            latch.countDown();
		            
		        }
	    });
        }catch(Exception e){
        	mesLogger.error(toMesMsg.toString());
        	mesLogger.error(frMesMsg.append("--> frMES: ").append(e.toString()).toString());
        }finally{
        	try {
    	        latch.await();
				httpClient.close();
    	    } catch (InterruptedException e) {
    	        e.printStackTrace();
    	    } catch(IOException e){
    	    	e.printStackTrace();
    	    }
    	   
        }
    }*/
}
